package com.jiyinit.web.core.business.controller;

import com.jiyinit.core.framework.base.entity.ResponseDto;
import com.jiyinit.core.framework.base.util.Check;
import com.jiyinit.core.framework.base.util.JsonEntityTransform;
import com.jiyinit.core.framework.base.util.LogUtil;
import com.jiyinit.web.core.business.dto.DailyLogRequest;
import com.jiyinit.web.core.business.dto.MessageRequest;
import com.jiyinit.web.core.business.dto.UserTaskRequest;
import com.jiyinit.web.core.business.entity.TabCoreTask;
import com.jiyinit.web.core.business.entity.TabCoreTaskMessage;
import com.jiyinit.web.core.business.service.DailyLogServiceImpl;
import com.jiyinit.web.core.business.service.TaskMessageServiceImpl;
import com.jiyinit.web.core.business.service.UserTaskServiceImpl;
import com.jiyinit.web.core.business.vo.UserTaskVo;
import com.jiyinit.web.core.common.logic.ParamCheckLogic;
import com.jiyinit.web.core.common.logic.ValidateResult;
import com.jiyinit.web.core.common.util.UserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

/**
 * Created by user1 on 2019/2/26.
 */
@Controller
@RequestMapping(value = "/workLogByPC")
public class WorkLogContrller {

    /**
     * 日志
     */
    private static Logger logger = LoggerFactory.getLogger(WorkLogContrller.class);

    @Resource(name = "core.paramCheckLogic")
    private ParamCheckLogic paramCheckLogic;

    @Resource(name ="core.dailyLogService")
    private DailyLogServiceImpl dailyLogService;

    @Resource(name = "core.userTaskServiceImpl")
    private UserTaskServiceImpl userTaskService;

    @Resource(name = "core.taskMessageServiceImpl")
    private TaskMessageServiceImpl taskMessageService;

    @RequestMapping(value = "/toAddWorkLog")
    public String toAddWorkLog(){
        return "workLog/addWorkLog";
    }

    /**
     * PC端保存日志接口
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addWorkLog")
    public ResponseEntity<ResponseDto> addWorkLog(HttpServletRequest request){
        DailyLogRequest dailyLogRequest = new DailyLogRequest();
        Integer userId = UserUtil.getCurrentUser().getUserId();
        dailyLogRequest.setUserId(userId);

        if (dailyLogRequest.getUserId() == null) {
            return new ResponseEntity<>(ResponseDto.responseFail("会话超时, 请手动保存文字内容到记事本, 并刷新窗口"), HttpStatus.OK);
        }

        //检测是否创建了日志
        TabCoreTask task = dailyLogService.getDailyLogByUserId(dailyLogRequest.getUserId());
        if(Check.isNullObj(task)){
            return new ResponseEntity<>(ResponseDto.responseFail("你还未创建日志, 请用移动端简单任务创建完成后, 再使用PC端"), HttpStatus.OK);
        }

        //检测是否指定阅读者
        UserTaskRequest userTaskRequest = new UserTaskRequest();
        userTaskRequest.setTaskId(task.getTaskId());
        List<UserTaskVo> alltors = userTaskService.finAll(userTaskRequest);
        if(Check.isNullCollection(alltors)){
            return new ResponseEntity<>(ResponseDto.responseFail("你未指定阅读者, 请指定阅读者后继续"), HttpStatus.OK);
        }

        //组装添加日志请求
        MessageRequest msgReq = new MessageRequest();
        String content = request.getParameter("content");
        if(content.length() > 500){
            return new ResponseEntity<>(ResponseDto.responseFail("日志内容不能超过500个字符!"), HttpStatus.OK);
        }
        msgReq.setContent(content);
        msgReq.setId(task.getTaskId());
        msgReq.setUserId(userId);
        msgReq.setFunId(22);
        msgReq.setIsPush(1);
        //检测今天有没有添加日志
        TabCoreTaskMessage message = taskMessageService.findTodayMessage(task.getTaskId());
        if(!Check.isNullObj(message) && !Check.isNullObj(message.getTaskMessageId())){
            msgReq.setTaskMessageId(message.getTaskMessageId());
        }else{
            msgReq.setTaskMessageId(null);
        }

        int num = taskMessageService.addDailyLogMessage1(msgReq);
        if(num > 0){
            return new ResponseEntity<ResponseDto>(ResponseDto.responseOK("提交成功"), HttpStatus.OK);
        }
        return new ResponseEntity<ResponseDto>(ResponseDto.responseFail("系统未知异常"), HttpStatus.OK);
    }

    /**
     * 新建前的查询，该用户是否存在工作日志，不存在返回，存在则返回今天的工作日志的内容
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST,value = "checkAdd")
    public ResponseEntity<ResponseDto> checkAdd(HttpServletRequest request) {
        try {
            LogUtil.info(logger, "接口:{}", "/mobile/dailyLog/checkAdd");
            DailyLogRequest dailyLogRequest = new DailyLogRequest();
            dailyLogRequest.setUserId(UserUtil.getCurrentUser().getUserId());

            if (dailyLogRequest.getUserId() == null) {
                return new ResponseEntity<>(ResponseDto.responseFail("用户不能为空"), HttpStatus.OK);
            }

            TabCoreTask task = dailyLogService.getDailyLogByUserId(dailyLogRequest.getUserId());
            HashMap<String,Object> result = new HashMap<>();
            result.put("dailyLog",task);
            //联系人，今天的说说
            TabCoreTaskMessage message = null;
            List<UserTaskVo> alltors = null;
            if(task != null){
                UserTaskRequest userTaskRequest = new UserTaskRequest();
                userTaskRequest.setTaskId(task.getTaskId());
                alltors = userTaskService.finAll(userTaskRequest);
                message = taskMessageService.findTodayMessage(task.getTaskId());
            }
            result.put("alltors",alltors);
            result.put("message",message);

            LogUtil.info(logger, "接口:/mobile/dailyLog/checkAdd,返回结果{}", JsonEntityTransform.object2Json(result));
            return new ResponseEntity<>( ResponseDto.responseOK(result), HttpStatus.OK);
        }
        catch (Exception ex) {
            LogUtil.info(logger, "接口:/mobile/dailyLog/checkAdd,访问异常{}", ex.toString());
            return new ResponseEntity<>( ResponseDto.responseFail("接口请求异常"), HttpStatus.OK);
        }
    }

    /**
     * 添加工作日志说说（每天只有一条）
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST,value = "addMessage")
    public ResponseEntity<ResponseDto> addMessage(HttpServletRequest request, MessageRequest msgReq){
        LogUtil.info(logger, "接口:{}", "/mobile/dailyLog/addMessage");
        String logJson = request.getParameter("request_json");
        LogUtil.info(logger, "logJson:{}", logJson);
        MessageRequest messageRequest = (MessageRequest) JsonEntityTransform.json2Object(logJson, MessageRequest.class);
        if (messageRequest.getId() == null) {
            return new ResponseEntity<>(ResponseDto.responseFail("工作日志ID不能为空"), HttpStatus.OK);
        }
        if (messageRequest.getContent() == null && "".equals(messageRequest.getContent())) {
            return new ResponseEntity<>(ResponseDto.responseFail("说说内容不能为空"), HttpStatus.OK);
        }
        if (messageRequest.getContent().length()>500) {
            return new ResponseEntity<>(ResponseDto.responseFail("说说内容长度不能大于500"), HttpStatus.OK);
        }
        if (messageRequest.getIsPush()== null ) {
            return new ResponseEntity<>(ResponseDto.responseFail("是否推送不能为空"), HttpStatus.OK);
        }

        ValidateResult<MessageRequest> validateResult = paramCheckLogic.checkParamValidate(messageRequest);
        if (!validateResult.isSuccess()) {
            return new ResponseEntity<>(validateResult.getDto(), HttpStatus.OK);
        }

        int num = taskMessageService.addDailyLogMessage1(messageRequest);

        if(num > 0)
            return new ResponseEntity<>( ResponseDto.responseOK(""), HttpStatus.OK);
        return new ResponseEntity<>( ResponseDto.responseFail("新建失败！"), HttpStatus.OK);
    }

    /**
     * 创建工作日志
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST,value = "add")
    public ResponseEntity<ResponseDto> add(HttpServletRequest request){
        LogUtil.info(logger, "接口:{}", "/mobile/dailyLog/add");
        DailyLogRequest dailyLogRequest = getJsonToTaskRequest(request);
        if (dailyLogRequest.getChannel() == null) {
            return new ResponseEntity<>(ResponseDto.responseFail("渠道不能为空"), HttpStatus.OK);
        }
        if (dailyLogRequest.getAlloterIds() == null) {
            return new ResponseEntity<>(ResponseDto.responseFail("联系人不能为空"), HttpStatus.OK);
        }
        if (dailyLogRequest.getTitle() == null && "".equals(dailyLogRequest.getTitle())) {
            return new ResponseEntity<>(ResponseDto.responseFail("标题不能为空"), HttpStatus.OK);
        }
        //每个人只能有一个工作日志
        TabCoreTask dailyLog =  dailyLogService.getDailyLogByUserId(dailyLogRequest.getUserId());
        if(dailyLog != null)  return new ResponseEntity<>( ResponseDto.responseFail("已存在工作日志！"), HttpStatus.OK);

        int num = dailyLogService.add(dailyLogRequest);
        if(num > 0)
        {
            return new ResponseEntity<>( ResponseDto.responseOK(""), HttpStatus.OK);
        }
        return new ResponseEntity<>( ResponseDto.responseFail("新建失败！"), HttpStatus.OK);
    }


    private DailyLogRequest getJsonToTaskRequest(HttpServletRequest request){
        String logJson = request.getParameter("request_json");
        LogUtil.info(logger, "logJson:{}", logJson);
        DailyLogRequest dailyLogRequest = JsonEntityTransform.json2Object(logJson, DailyLogRequest.class);
        return dailyLogRequest;
    }


}
